package online.heycm.platform.web.common.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import online.heycm.platform.common.entity.result.Result;
import online.heycm.platform.common.tools.IOUtil;
import org.springframework.core.Ordered;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * @author heycm
 * @since 2023/12/11 14:39
 */
public class MethodFilter extends OncePerRequestFilter implements Ordered {

    private final int order;

    private final String[] methods;

    public MethodFilter(int order) {
        this.order = order;
        methods = new String[]{"GET", "POST"};
    }

    public MethodFilter(int order, String[] methods) {
        this.order = order;
        this.methods = methods;
    }

    @Override
    public int getOrder() {
        return order;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        if (!supportedMethods(request, response)) {
            return;
        }
        chain.doFilter(request, response);
    }

    private boolean supportedMethods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (methods == null) {
            notSupportedMethods(request, response);
            return false;
        }
        for (String method : methods) {
            if (request.getMethod().equalsIgnoreCase(method)) {
                return true;
            }
        }
        notSupportedMethods(request, response);
        return false;
    }

    private void notSupportedMethods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Result<Object> result = Result.error("不支持的请求方式: " + request.getMethod());
        IOUtil.writeJson(response, result);
    }
}
